import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

export const loadTranslations = createAsyncThunk(
  'lang/loadTranslations',
  async (lang) => {
    const data = await import(`../locales/${lang}.json`)
    return { lang, translations: data.default }
  }
)

const initialState = {
  lang: 'jp',
  translations: {},
  loading: false
}

export const langSlice = createSlice({
  name: 'lang',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(loadTranslations.pending, (state) => {
        state.loading = true
      })
      .addCase(loadTranslations.fulfilled, (state, action) => {
        state.lang = action.payload.lang
        state.translations = action.payload.translations
        state.loading = false
        localStorage.setItem('preferredLang', action.payload.lang)
      })
      .addCase(loadTranslations.rejected, (state) => {
        state.loading = false
      })
  }
})

export default langSlice.reducer